package com.hmkj.core.api.alibaba;

import com.aliyun.oss.OSSClient;
import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.service.cache.RedisService;
import com.xiaoleilu.hutool.http.HttpUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.function.Consumer;

public class AliyunOSSClient {

    private static RedisService redisService = SpringContextUtils.getBean(RedisService.class);
    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String BASE_PATH;
    private static String BUCKET_NAME;

    static {
        endpoint = redisService.get(ConfigNID.OSS_ENDPOINT);
        accessKeyId = redisService.get(ConfigNID.OSS_ACCESSKEY_ID);
        accessKeySecret = redisService.get(ConfigNID.OSS_ACCESSKEY_SECRET);
        BASE_PATH = "otc_futu";
        BUCKET_NAME = redisService.get(ConfigNID.OSS_BUCKET_NAME);
    }

    /**
     * 上传文件
     *
     * @param file_buff
     * @param filePath
     * @return
     */
    public static String uploadFile(final byte[] file_buff, final String filePath) {
        final String path = BASE_PATH + filePath;
        ossClient(o -> o.putObject(BUCKET_NAME, path, new ByteArrayInputStream(file_buff)));
        return path;
    }


    /**
     * 上传文件
     *
     * @param file
     * @param filePath
     * @return
     */
    public static String uploadFile(final File file, final String filePath) {
        final String path = BASE_PATH + filePath;
        ossClient(o -> o.putObject(BUCKET_NAME, path, file));
        return path;
    }

    /**
     * 下载文件
     *
     * @param path 相对路径
     * @return
     */
    public static byte[] downloadFile(String path) {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            String uri = "http://" + BUCKET_NAME + "." + endpoint.substring(7, endpoint.length());
            HttpUtil.download(uri + path, stream, true);
            return stream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void ossClient(Consumer<OSSClient> consumer) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            consumer.accept(ossClient);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        } finally {
            // 关闭client
            ossClient.shutdown();
        }
    }

}

